package com.jy.wms.controller;

import com.github.pagehelper.Page;
import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.SetStatus;
import com.jy.wms.common.base.*;
import com.jy.wms.pojo.*;
import com.jy.wms.service.WmsStockMoveService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: WmsStockMoveController
 * @Description: 库存移动管理
 * @Author Yjs
 * @Date Tue Nov 21 17:13:14 GMT+08:00 2017
 */
@RestController
@RequestMapping("/wmsstockmove")
@Api(value = "/wmsstockmove", description = "关于库存移动管理操作")
public class  WmsStockMoveController extends BaseController<WmsStockMoveService,WmsStockMove> {
    /**
     * 查询库存移动管理
     * @param entity
     * @param session
     * @return
     */
    @PostMapping(value = {"list"})
    @ApiOperation(value = "查询库存移动管理",response = JSONObject.class, notes = "查询库存移动信息")
    public @ResponseBody JSONObject getWmsStockMove(@RequestBody WmsStockMove entity, HttpSession session) {
        JSONObject json = new JSONObject();
        Page<WmsStockMove> list = new Page<WmsStockMove>();
        try{
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            String ckid= String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库编号
            List<SysHz> hz= (List<SysHz>) session.getAttribute(BaseSessionInfo.SessionConsignor);//货主信息
            if(hz.size()>0){
                if (entity.getStime() != null && !entity.getStime().equals("")) {
                    String[] line = entity.getStime().split("~");
                    entity.setStime(line[0].trim());
                    entity.setEtime(line[1].trim());
                }
                entity.setCkid(ckid);
                entity.setHzid(hz.get(0).getHzid());
                list= baseService.baseSelectPage(entity);
            }
            json = SetStatus.setSearchType(JSONArray.fromObject(list).toString(),(int) list.getTotal());
        }catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 作废库存移动信息
     * @param setAndModifyModel
     * @param session
     * @return
     */
    @PostMapping(value = "delete")
    @ApiOperation(value = "作废库存移动信息",response = JSONObject.class, notes = "作废库存移动信息")
    public @ResponseBody
    JSONObject deleteWmsStockMove(@RequestBody SetAndModifyModel setAndModifyModel, HttpSession session) {
        JSONObject jsonObject = new JSONObject();
        try {
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            baseService.baseDeleteBathPrimaryKeys(setAndModifyModel.getIds(), userinfo.getUser().getName());
        }catch (SucessException e) {
            e.printStackTrace();
            jsonObject = SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(),"作废库存移动信息成功","","");
        }catch (RuntimeException e) {
            e.printStackTrace();
            jsonObject = SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(),"作废库存移动信息失败",e.getMessage(),"");
        }catch (ServiceException e) {
            e.printStackTrace();
            jsonObject = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.warning.toString(),"作废库存移动信息失败",e.getMessage(),"");
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(),"作废库存移动信息失败",e.getMessage(),"");
        }
        return jsonObject;
    }

    /**
     * 新增库存移动
     * @param entity
     * @param session
     * @return
     */
    @PostMapping(value = "add")
    @ApiOperation(value = "新增库存移动信息",response = JSONObject.class, notes = "新增库存移动信息")
    public @ResponseBody JSONObject addWmsStockMove(@RequestBody WmsStockMove entity, HttpSession session) {
        JSONObject jsonObject = new JSONObject();
        try {
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            String ckid= String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库编号
            List<SysHz> hz= (List<SysHz>) session.getAttribute(BaseSessionInfo.SessionConsignor);//货主信息
            if(hz.size()>0) {
                entity.setHzid(hz.get(0).getHzid());
                entity.setCkid(ckid);
                //创建人
                entity.setCjry(userinfo.getUser().getName());
                baseService.baseInsert(entity);
            }
        }catch (SucessException e) {
            e.printStackTrace();
            jsonObject = SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(),"新增库存移动成功","",JSONObject.fromObject(entity).toString());
        }catch (RuntimeException e) {
            e.printStackTrace();
            jsonObject = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.warning.toString(),"新增库存移动失败",e.getMessage(),"");
        }catch (ServiceException e) {
            e.printStackTrace();
            jsonObject = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.warning.toString(),"新增库存移动失败",e.getMessage(),"");
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(),"新增库存移动失败",e.getMessage(),"");
        }
        return jsonObject;
    }

    /**
     * 编辑查看库存移动信息
     * @param id
     * @return
     */
    @GetMapping(value = "getWmsStockMove/{id}")
    @ApiOperation(value = "查看库存移动信息",response = JSONObject.class, notes = "GET查看库存移动信息")
    public @ResponseBody JSONObject getWmsStockMoveById(@PathVariable("id") String id) {
        JSONObject json = new JSONObject();
        try{
            //移动状态 0：未确认 1：已确认 2：作废
            Integer ydzt=0;
            WmsStockMove entity=baseService.getWmsStockMoveById(id,ydzt);
            if(entity!=null){
                json = JSONObject.fromObject(entity);
            }else{
                json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(),"查看库存移动信息","请选择移动状态为未确认的库存移动数据","");
            }
        } catch (Exception e) {
            e.printStackTrace();
            //json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.error.toString(),"查看库存移动信息","查看库存移动信息失败","");
        }
        return json;
    }
    /**
     * 编辑查看库存移动明细信息
     * @param wmsStockMove
     * @return
     */
    @PostMapping(value = "getWmsStockMoveDetail")
    @ApiOperation(value = "查看库存移动明细信息",response = JSONObject.class, notes = "Post查看库存移动明细信息")
    public @ResponseBody JSONObject getWmsStockMoveDetailById(@RequestBody WmsStockMove wmsStockMove) {
        JSONObject json = new JSONObject();
        Page<WmsStockMoveDetailed> list = new Page<WmsStockMoveDetailed>();
        try{
            list=baseService.getWmsStockMoveDetailById(wmsStockMove);
            json = SetStatus.setSearchType(JSONArray.fromObject(list).toString(),(int) list.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
            // json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(),ReturnType.error.toString(),"查看库存移动明细信息",e.getMessage(),"");
        }
        return json;
    }
    /**
     * 编辑页面(添加明细)
     * @param wmsStockMove
     * @return
     */
    @PostMapping(value = "bjSaveMx")
    @ApiOperation(value = "编辑页面添加明细",response = JSONObject.class, notes = "Post添加明细")
    public @ResponseBody
    JSONObject bjSaveMx(@RequestBody WmsStockMove wmsStockMove, HttpSession session) {
        JSONObject json = new JSONObject();
        try{
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            String ckid= String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库编号
            List<SysHz> hz= (List<SysHz>) session.getAttribute(BaseSessionInfo.SessionConsignor);//货主信息
            if(hz.size()>0) {
                wmsStockMove.setHzid(hz.get(0).getHzid());
                wmsStockMove.setCkid(ckid);
                baseService.bjSaveMx(wmsStockMove);
            }
            json = SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "新增库存移动明细成功", "", JSONObject.fromObject(wmsStockMove).toString());
        }catch (RuntimeException e) {
            e.printStackTrace();
            json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.warning.toString(),"新增库存移动明细失败",e.getMessage(),"");
        }catch (ServiceException e) {
            e.printStackTrace();
            json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.warning.toString(),"新增库存移动明细失败",e.getMessage(),"");
        }catch (Exception e) {
            e.printStackTrace();
            json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(),"新增库存移动明细失败",e.getMessage(),"");
        }
        return json;
    }
    /**
     * 编辑页面(保存按钮)
     * @param wmsStockMove
     * @return
     */
    @PostMapping(value = "baseUpdateByPrimaryKey")
    @ApiOperation(value = "编辑页面保存库存移动信息",response = JSONObject.class, notes = "Post添加明细")
    public @ResponseBody JSONObject baseUpdateByPrimaryKey(@RequestBody WmsStockMove wmsStockMove, HttpSession session) {
        JSONObject json = new JSONObject();
        try{
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            //修改人
            wmsStockMove.setXgry(userinfo.getUser().getName());
            baseService.baseUpdateByPrimaryKey(wmsStockMove);
        }catch (SucessException e) {
            e.printStackTrace();
            json = SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(),"编辑库存移动成功","",JSONObject.fromObject(wmsStockMove).toString());
        }catch (RuntimeException e) {
            e.printStackTrace();
            json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.warning.toString(),"编辑库存移动失败",e.getMessage(),"");
        }catch (ServiceException e) {
            e.printStackTrace();
            json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.warning.toString(),"编辑库存移动失败",e.getMessage(),"");
        }catch (Exception e) {
            e.printStackTrace();
            json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(),"编辑库存移动失败",e.getMessage(),"");
        }
        return json;
    }
    /**
     * 编辑页面(删除明细)
     * @param setAndModifyModel
     * @return
     */
    @PostMapping(value = "bjDeleteMx")
    @ApiOperation(value = "编辑页面删除明细",response = JSONObject.class, notes = "Post删除明细")
    public @ResponseBody JSONObject bjDeleteMx(@RequestBody SetAndModifyModel setAndModifyModel) {
        JSONObject json = new JSONObject();
        try{
            baseService.bjDeleteMx(setAndModifyModel);
            json = SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "删除库存移动明细成功", "", "");
        }catch (RuntimeException e) {
            e.printStackTrace();
            json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.warning.toString(),"删除库存移动明细失败",e.getMessage(),"");
        }catch (ServiceException e) {
            e.printStackTrace();
            json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.warning.toString(),"删除库存移动明细失败",e.getMessage(),"");
        }catch (Exception e) {
            e.printStackTrace();
            json = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(),"删除库存移动明细失败",e.getMessage(),"");
        }
        return json;
    }
    /**
     * 目标库位：
     * 1.货品没有绑定库位组
     * 目标库位可以选择库位属性为“正常/管控”
     * 保存时要验证该库位货品是否可以混放,相同货品批次是否可以混放
     * 2.货品绑定库位组
     * 目标库位必须在货品绑定的库位组内的库位
     * 库位的属性为“正常/管控”
     * 保存时要验证该库位货品是否可以混放,相同货品批次是否可以混放
     * 库位查询
     * @param session
     * @return
     */
    @PostMapping(value = "searchKw")
    @ApiOperation(value = "库位查询信息", response = JSONObject.class, notes = "库位查询{\"hpbh\":\"货品编号\",\"show_ydhkwid\":\"库位名称模糊查询\"}")
    public @ResponseBody
    JSONArray searchKw(@RequestBody Map<String, String> map, HttpSession session) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject=null;
        UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        String ckId= String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库编号
        String hzId=null;
        List<SysHz> hz= (List<SysHz>) session.getAttribute(BaseSessionInfo.SessionConsignor);//货主信息
        if(hz.size()>0){
            hzId=hz.get(0).getHzid();
            //查询货品信息
            List<WmsGoods> wmsGoodsList = baseService.searchHp(map.get("hpbh").toString());
            //空库位集合
            List<WmsLibraryPosition> list;
            //有效库位
            String sfyx="1";
            //存储库位
            String lx="0";
            //货品没有绑定库位组
            //查询属性为“正常/管控”,并且有效的库位
            List<String> stringList = new ArrayList<>();
            //属性为“正常"
            stringList.add("0");
            //属性为“管控”
            stringList.add("2");
            String glkwzid = "1";
            if (wmsGoodsList.size()>0) {

            } else {
                glkwzid = "0";
            }
            if ("0".equals(glkwzid)) {
                list = baseService.searchKw(stringList, lx, sfyx, hzId, ckId, map.get("show_ydhkwid"));
            }else{
                //货品绑定库位组
                list = baseService.searchKwMx(wmsGoodsList, stringList, lx, sfyx, hzId, ckId, map.get("show_ydhkwid"));
            }
            for(WmsLibraryPosition wmsLibraryPosition : list){
                jsonObject = new JSONObject();
                jsonObject.put("ydhkwid",wmsLibraryPosition.getId());
                jsonObject.put("show_ydhkwid",wmsLibraryPosition.getMc());
                jsonArray.add(jsonObject);
            }
        }
        return jsonArray;
    }

    /**
     * 查询可移动库存货品
     * @param wmsStockMoveDetailed
     * @return
     */
    @PostMapping(value = "searchKc")
    @ApiOperation(value = "查询可移动库存货品",response = JSONObject.class, notes = "查询可移动库存货品")
    public @ResponseBody JSONObject searchKc(@RequestBody WmsStockMoveDetailed wmsStockMoveDetailed, HttpSession session) {
        JSONObject jsonObject = new JSONObject();
        Page<WmsStockMoveDetailed> list = new Page<WmsStockMoveDetailed>();
        try{
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            String ckId= String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库编号
            String hzId=null;
            List<SysHz> hz= (List<SysHz>) session.getAttribute(BaseSessionInfo.SessionConsignor);//货主信息
            if(hz.size()>0) {
                if (wmsStockMoveDetailed.getHpscrq_start() != null && !wmsStockMoveDetailed.getHpscrq_start().equals("")) {
                    String[] line = wmsStockMoveDetailed.getHpscrq_start().split("~");
                    wmsStockMoveDetailed.setHpscrq_start(line[0]);
                    wmsStockMoveDetailed.setHpscrq_end(line[1]);
                }

                wmsStockMoveDetailed.setCkid(ckId);
                wmsStockMoveDetailed.setHzid(hz.get(0).getHzid());
                list = baseService.searchKc(wmsStockMoveDetailed);
            }
            jsonObject = SetStatus.setSearchType(JSONArray.fromObject(list).toString(),(int) list.getTotal());
        }catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
    /**
     * 库存移动确认保存
     * @param setAndModifyModel
     * @param session
     * @return
     */
    @PostMapping(value = "saveConfirm")
    @ApiOperation(value = "库存移动确认",response = JSONObject.class, notes = "库存移动确认")
    public @ResponseBody JSONObject saveConfirm(@RequestBody SetAndModifyModel setAndModifyModel, HttpSession session) {
        JSONObject jsonObject = new JSONObject();
        try {
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            //当前确认人
            String qrr=userinfo.getUser().getName();
            baseService.saveConfirm(qrr,setAndModifyModel.getIds());
        }catch (SucessException e) {
            e.printStackTrace();
            jsonObject = SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(),"库存移动确认成功","","");
        }catch (RuntimeException e) {
            e.printStackTrace();
            jsonObject = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.warning.toString(),"库存移动确认失败",e.getMessage(),"");
        }catch (ServiceException e) {
            e.printStackTrace();
            jsonObject = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.warning.toString(),"库存移动确认失败",e.getMessage(),"");
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(),"库存移动确认失败",e.getMessage(),"");
        }
        return jsonObject;
    }

    /**
     * 导出库存移动信息
     *
     * @param response
     * @param entity
     * @param session
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "导出库存移动信息", response = JSONObject.class, notes = "导出库存移动信息")
    @PostMapping(value = "exportWmsStockMove")
    public @ResponseBody
    JSONObject exportWmsStockMove(HttpServletResponse response, @RequestBody WmsStockMove entity, HttpSession session) throws IOException {
        String fileName = "库存移动信息";
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        //仓库id
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));
        entity.setCkid(ckid);
        //货主信息
        List<SysHz> hz = (List<SysHz>) session.getAttribute(BaseSessionInfo.SessionConsignor);
        String hzid = null;
        if (hz.size() > 0) {
            hzid = hz.get(0).getHzid();
        }
        if (entity.getStime() != null && !entity.getStime().equals("")) {
            String[] line = entity.getStime().split("~");
            entity.setStime(line[0]);
            entity.setEtime(line[1]);
        }
        entity.setHzid(hzid);
        List<WmsStockMove> wmsStockMoveList = baseService.exportWmsStockMove(entity);
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 文件名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("库存移动信息", "UTF-8") + ".xls");
        response.setCharacterEncoding("UTF-8");
        ExportParams ep = new ExportParams();
        ep.setStyle(ManySheetOneSyler.class);
        Workbook workbook = ExcelExportUtil.exportExcel(ep, WmsStockMove.class, wmsStockMoveList);
        workbook.write(response.getOutputStream());
        return null;
    }
}
